import { LevelConfigInfo } from "../../Data/LevelConfig";
import { StaticData } from "../../Data/StaticData";
import { EventNames } from "../Data/EventNames";
import { LevelItemInfo } from "../Data/LevelItemInfo";

const { regClass, property } = Laya;

@regClass()
export class LevelItem extends Laya.Script {

    /**关卡背景图 */
    private imgLevelIcon: Laya.Image;
    /**成功通关状态 */
    private imgSuccessState: Laya.Image;
    /**未通关状态 */
    private imgFailState: Laya.Image;
    /**关卡名文本 */
    private labelLevelName: Laya.Label;
    /**选择关卡信息 */
    private lavelItemInfo: LevelItemInfo;

    onEnable(): void {
    }

    onAwake(): void {
        this.findComponent();
    }

    onStart(): void {
        this.addEventListener();
    }

    onDestroy(): void {
        this.removeEventListener();
    }
    /**刷新页面信息 */
    public updateInfo(data: LevelItemInfo) {
        this.lavelItemInfo = data;
        this.imgLevelIcon.skin = data.levelIconSrc;
        this.labelLevelName.text = data.levelName;
        this.modifyPassLevelState(data.passLevelState);
    }


    private findComponent(): void {
        this.imgLevelIcon = this.owner.getChildByName("imgLevelIcon") as Laya.Image;
        this.imgSuccessState = this.owner.getChildByName("imgSuccessState") as Laya.Image;
        this.imgFailState = this.owner.getChildByName("imgFailState") as Laya.Image;
        this.labelLevelName = this.owner.getChildByName("down").getChildByName("labelLevelName") as Laya.Label;
        this.modifyPassLevelState(false);
    }

    private addEventListener(): void {
        this.owner.on(Laya.Event.CLICK, this, this.onClickLevelItem);
    }

    private removeEventListener(): void {
        this.owner.off(Laya.Event.CLICK, this, this.onClickLevelItem);
    }
    /**监听点击关卡 */
    private onClickLevelItem(): void {

        if (StaticData.jumpLevel) {
            console.log("跳关", StaticData.jumpLevel);
            StaticData.getLevelConfig(StaticData.jumpLevel, (config: LevelConfigInfo) => {
                if (!config) {
                    console.log("关卡配置异常");
                    return
                }
                Laya.stage.event(EventNames.GAME_OPEN_LEVEL, config);
            })
            return;
        }

        Laya.SoundManager.playSound("resources/Audio/audioClick.mp3", 1);
        StaticData.getLevelConfig(this.lavelItemInfo.levelId, (config: LevelConfigInfo) => {
            if (!config) {
                console.log("关卡配置异常");
                return
            }
            Laya.stage.event(EventNames.GAME_OPEN_LEVEL, config);
        })
    }
    /**修改通关状态 */
    private modifyPassLevelState(passState: boolean): void {
        this.imgSuccessState.visible = passState;
        this.imgFailState.visible = !passState
    }
}